<template>
  <table>
    <thead>
      <tr>
        <th v-for="(title, idx) in titles" :key="idx">{{ title }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="([name, value], idx) in Object.entries(datasource)" :key="idx">
        <th>{{ name }}</th>
        <th>{{ getValue(name, value) }}</th>
      </tr>
    </tbody>
  </table>
</template>


<script>
export default {
  props: {
    datasource: {
      type: Object,
      required: true,
    },
    titles: {
      type: Array,
      default: () => ["指标名称", "指标值"],
    },
    unit: {
      type: String,
      default: ''
    }
  },
  methods: {
    getValue(name, value) {
      if (this.unit == '%') {
        return value === '' ? '-----' : `${(Number(value) * 100).toFixed(2)}%`
      } else {
        const unit = name.includes('%') ? '%' : ''
        if (typeof value == "number") {
          return `${(value).toFixed(2)}${unit}`;
        } else {
          const _value = value.trim();
          if (value === "") {
            return "-----";
          } else {
            const num = Number(_value);
            return `${isNaN(num) ? _value : num.toFixed(2)}${unit}`;
          }
        }
      }
    },
  },
};
</script>


<style lang="less" scoped>
table {
  margin: 0.2rem auto;
  width: 100%;
  font-size: 0.9em;
  font-weight: 500;
  border-spacing: 0px;
  border-collapse: collapse;
  color: #333;
}

thead,
tfoot {
  font-size: 0.2rem;
  color: #fff;
  background-color: #5b9bd5;
}

tbody > tr {
  border-bottom: 1px solid #eeeeee;
}

tbody > tr:nth-child(2n + 1) {
  background-color: #d2deef;
}

tbody > tr:nth-child(2n) {
  background-color: #eaeff7;
}

tbody > tr:hover {
  // background-color: #f8f8f8;
  color: red;
  background-color: #5b9bd599;
}

th,
td {
  padding: 0 0.05rem;
  text-align: center;
  line-height: 2.5em;
  border: 1px solid #fff;
}
</style>